package com.opener.common.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.opener.common.utils.JsonUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Model implements Serializable{

	public Object deepClone(){
		try {
			//将对象写到流里
			ByteArrayOutputStream bo=new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(this);
			//从流里读出来
			ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
			ObjectInputStream oi=new ObjectInputStream(bi);
			Object copy = oi.readObject();
			oi.close();
			bi.close();
			oo.close();
			bo.close();
			return copy;

		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 */
	@Override
	public String toString(){
		String s = JsonUtils.toString(this);
		return s;
	}
	public Map<String,Object> toMap(){
		return toMapIgnoreFields();
	}
	public Map<String,Object>toMapIgnoreFields(String ...ignoreFields){
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		Map map = mapper.convertValue(this,HashMap.class);
		if (ignoreFields != null && ignoreFields.length>0){
			for (String k : ignoreFields){
				map.remove(k);
			}
		}
		return map;
	}
}
